package com.demo.user.service.handler.transfer;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.demo.user.entity.DeptInfo;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author : YU.TAN
 * @date : 2021/8/27 10:42
 */
@Slf4j
public abstract class BaseTransferProcess<E> implements TransferProcess {

    protected final BaseMapper<E> baseMapper;

    protected BaseTransferProcess(BaseMapper<E> baseMapper) {
        this.baseMapper = baseMapper;
    }

    protected abstract LambdaQueryWrapper<E> getQuery(Long userId);

    protected abstract E getUpdate(Long newUserId);

    @Override
    public List<Long> load(Long userId) {
        LambdaQueryWrapper<E> query = getQuery(userId);
        if (query==null){
            return new ArrayList<>();
        }
        List<Map<String, Object>> selectMaps = baseMapper.selectMaps(query);
        List<Long> ids = new ArrayList<>(selectMaps.size());
        for (Map<String, Object> map : selectMaps) {
            Long id = (Long) map.get(ID_FIELD);
            ids.add(Long.parseLong(Objects.toString(map.get(ID_FIELD))));
        }
        log.info("查询到需要更新的数据:{}",ids);
        return ids;
    }

    @Override
    public void transfer(List<Long> ids, Long newUserId) {
        QueryWrapper<E> wrapper = new QueryWrapper<E>().in("id", ids);
        //获取修改对象
        E update = getUpdate(newUserId);
        log.info("更新的实体对象：{}", JSON.toJSONString(update));
        int i = baseMapper.update(update, wrapper);
        log.info("更新完成，受影响的行数：{}",i);
    }


}
